#include "Service.h"
#include "OpHandler.h"

static void 
_fault(ChunkOp* op, RdmaRpc *rpc) 
{
    //TODO: free all resource pre-allocated for this request and notify client
    op->dss_response->status_code = UNSUPPORTED_TYPE;
    rpc->RpcServiceComplete(op->rpc_ex);
    rpc->FreePiece(op);
}


/*void 
cs_client_auth_service(void* self, void* ex, void* cs)
{
    return;
}*/
void 
cs_object_io_service(void* self, void* ex, void* cs)
{
    RdmaRpc *rpc = static_cast<RdmaRpc*>(self);
    RpcExecution *exec = static_cast<RpcExecution*>(ex);
    ChunkServer *chunk_server = static_cast<ChunkServer*>(cs);

    ChunkOp *op = static_cast<ChunkOp*>(rpc->AllocPiece());
    RpcMsg *rpc_resp = exec->resp_msg;
    RpcMsg *rpc_req = exec->req_msg;
    struct dss_msg *msg = reinterpret_cast<struct dss_msg*>(rpc_req->data);
    memset(op, 0, sizeof(ChunkOp));
    op->rpc_ex = exec;
    op->cs_self = chunk_server;
    op->dss_request = msg;
    op->dss_response = reinterpret_cast<struct dss_msg*>(rpc_resp->data);

    op->dss_response->client_id = op->dss_request->client_id;
    //msg_type in response is always equal to msg_type in request add 1 

    op->dss_response->msg_type = op->dss_request->msg_type + 1u;
    op->dss_response->msg_id = op->dss_request->msg_id;

    switch (msg->msg_type)
    {
    case CHUNK_OP_CREATE:
        handle_op_create(op);
        //printf("handle create op\n");
        break;
    case CHUNK_OP_DELETE:
        handle_op_delete(op);
        //printf("handle delete op\n");

        break;
    case CHUNK_OP_READ:
        handle_op_read(op);
        //printf("handle read op\n");

        break;
    case CHUNK_OP_WRITE:
        handle_op_write(op);
        //printf("handle write op\n");

        break;
    default:
        printf("unrecoginized op\n");
        _fault(op, rpc);
        break;
    }
    return;
}
